package com.irdstudio.efp.nls.service.impl.psd.credit;

import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.SpringContextUtils;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.sequence.service.DefaultPatternDescriptor;
import com.irdstudio.basic.sequence.service.PatternDescriptor;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.impl.sx.CreditSoltServiceImpl;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

import static com.irdstudio.basic.sequence.service.DefaultPatternDescriptor.*;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/12/2
 * 功能描述:
 * 修改日期:2019/12/2
 * 修改描述:
 */
@Service("psdGenerateLmtService")
public class PsdGenerateLmtServiceImpl extends CreditSoltServiceImpl implements FrameworkService {
    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(PsdGenerateLmtServiceImpl.class);
    /**
     * 日志模板
     */
    private final String msgTemplate = "message{}";
    /**
     * 额度流水生成PATTERN
     */
    private static final PatternDescriptor PATTERN = DefaultPatternDescriptor.of("lmt" + YEAR_4 + MONTH + DAY + SEQ, 8);


    @Override
    protected void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsCreditInfoVO nlsCreditInfoVO) throws Exception {
        // 流水号
        String applySeq = nlsProcessBizVo.getApplySeq();
        logger.info("======>普税贷生成额度信息服务开始,流水号" + applySeq + "<======");

        try {
            // 根据授信申请流水号查询额度信息是否存在
            boolean isLimitExits = getLimitByLmtApplySeq(nlsCreditInfoVO);
            // 不存在则，插入一条未生效的额度信息
            if (isLimitExits) {
                insertProLmtCont(nlsCreditInfoVO);
            }
            // 更新授信申请 授信状态为通过
            //updateCreditApplyInfo(nlsCreditInfoVO);

        } catch (Exception e) {
            nlsProcessBizVo.setExceptionFlag(Boolean.TRUE);
            nlsProcessBizVo.setRefuseMsg(e.getMessage());
            nlsProcessBizVo.setExceptionMsg(e);
        } finally {
            logger.info("======>普税贷生成额度信息服务结束,流水号" + applySeq + "<======");
        }

    }

    /**
     * 更新授信状态为通过: <br>
     * <p>
     * 0.1:caoxin:2019/4/23 10:21: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/4/23 10:21
     * @version 0.1
     * @since 2019/4/23 10:21
     */

    private void updateCreditApplyInfo(NlsCreditInfoVO nlsCreditInfoVO) throws BizException {
        // 更新授信状态为通过
        nlsCreditInfoVO.setApprvSts(ConsoleConstant.NLSCREDIT_PASS);
        // 设置更新默认值
        setServerUpdateDefaultProperty(nlsCreditInfoVO);
        int result = nlsCreditInfoService.updateByPk(nlsCreditInfoVO);
        if (result == -1) {
            throw new BizException("更新授信信息失败");
        }
    }

    /**
     * 插入未生效的额度信息: <br>
     * <p>
     * 0.1:caoxin:2019/4/23 9:54: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/4/23 9:54
     * @version 0.1
     * @since 2019/4/23 9:54
     */

    private void insertProLmtCont(NlsCreditInfoVO nlsCreditInfoVO) throws BizException {
        // 网贷申请信息不能为空
        Objects.requireNonNull(nlsCreditInfoVO, "【额度生成插槽】授信申请信息为空!!!");
        LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
        // 生成Lmt流水号
        lmtPrdContVO.setLmtContNo(generateLmtContNo());
        // 来源授信申请信息 授信申请流水号
        lmtPrdContVO.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        // 来源授信申请信息 客户ID
        lmtPrdContVO.setCusId(nlsCreditInfoVO.getCusId());
        // 来源授信申请信息 客户姓名
        lmtPrdContVO.setCusName(nlsCreditInfoVO.getCusName());
        // 来源授信申请信息 客户证件类型
        lmtPrdContVO.setCertType(nlsCreditInfoVO.getCertType());
        // 来源授信申请信息 客户身份证
        lmtPrdContVO.setCertCode(nlsCreditInfoVO.getCertCode());
        // 来源授信申请信息 渠道号
        lmtPrdContVO.setChannelNo(nlsCreditInfoVO.getChannelNo());
        // 来源授信申请信息 产品ID
        lmtPrdContVO.setPrdId(nlsCreditInfoVO.getPrdId());
        // 来源授信申请信息 产品编号
        lmtPrdContVO.setPrdCode(nlsCreditInfoVO.getPrdCode());
        // 来源授信申请信息 产品名称
        lmtPrdContVO.setPrdName(nlsCreditInfoVO.getPrdName());
        // 来源授信申请信息 审批金额
        lmtPrdContVO.setLmtAmt(nlsCreditInfoVO.getApproveAmt());
        // 来源授信申请信息 可用额度
        lmtPrdContVO.setAvailAmt(nlsCreditInfoVO.getApproveAmt());
        // 来源授信申请信息 是否循环
        lmtPrdContVO.setCyclicFlg(nlsCreditInfoVO.getCyclicFlg());
        // 来源授信申请信息 币种
        lmtPrdContVO.setCurrencyType(nlsCreditInfoVO.getCurrencyType());
        // 来源授信申请信息 期限
        lmtPrdContVO.setTerm(new BigDecimal(nlsCreditInfoVO.getApplyTerm()));
        // 来源授信申请信息 期限类型
        lmtPrdContVO.setTermType(nlsCreditInfoVO.getTermType());
        // 来源授信申请信息 担保方式
        lmtPrdContVO.setAssureMeansMain(nlsCreditInfoVO.getAssureMeansMain());
        // 来源授信申请信息 贷款用途
        lmtPrdContVO.setLoanUse(nlsCreditInfoVO.getLoanUseType());
        // 来源授信申请信息 额度状态为未生效
        lmtPrdContVO.setLmtStatus(ConsoleConstant.LIMIT_STS_01);
        // 利率
        lmtPrdContVO.setRateY(nlsCreditInfoVO.getApproveRateY());

        String openday = pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001);
        // 起始日期
        lmtPrdContVO.setStartDate(openday);
        // 到期日期 openDay+期限
        try {
            lmtPrdContVO.setExpireDate(TimeUtil.addMonth(openday, 12));
        } catch (Exception e) {
            throw new BizException("【额度生成服务】授信协议表到期日期设置失败!!!");
        }

        setServerInsertDefaultProperty(lmtPrdContVO);
        lmtPrdContVO.setLegalOrgCode("0010");
        lmtPrdContVO.setLegalOrgName("广州银行智慧中心");
        int result = lmtPrdContService.insertLmtPrdCont(lmtPrdContVO);
        if (result == -1) {
            throw new BizException("=======>【额度生成服务】生成额度插槽,插入未生效的额度信息失败<=======", msgTemplate);
        }
    }

    /**
     * 通过授信申请流水号获取授信协议信息: <br>
     * <p>
     * 0.1:caoxin:2019/4/23 9:34: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/4/23 9:34
     * @version 0.1
     * @since 2019/4/23 9:34
     */

    private boolean getLimitByLmtApplySeq(NlsCreditInfoVO nlsCreditInfoVO) {
        LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
        lmtPrdContVO.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        lmtPrdContVO = lmtPrdContService.queryByPk(lmtPrdContVO);
        return lmtPrdContVO == null ? true : false;
    }


    /**
     * 生成LMT系统的交易流水号: <br>
     * <p>
     * 0.1:heyingfeng:2019/4/23 9:58: <br>
     *
     * @return
     * @author heyingfeng
     * @date 2019/4/23 9:58
     * @version 0.1
     * @since 2019/4/23 9:58
     */

    public String generateLmtContNo() {
        PatternedLimitableSeqService sequenceService = SpringContextUtils.getBean(PatternedLimitableSeqService.class);
        return sequenceService.getPatternedSequence("LMT", PATTERN);
    }


    /**
     * 额度信息服务
     */
    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    /**
     * 授信信息服务
     */
    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("psdAllotTaskHandleService")
    private PsdAllotTaskHandleServiceImpl psdAllotTaskHandleService;

    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;
}
